<?	/*
	// File:	init.inc.php
	// Purpose:	Authentication, Init sequence.
	// Creation:	2001-10-29
	// Author:	Felix <webmaster@can-host.com>
	*/
//
// Make sure that required PHP (php.ini) settings are on
if ($cfg['httpd_mode'] == 'apache') {
	if (!get_magic_quotes_gpc())
		echo "<b>magic_quotes_gpc</b> must be set to <b>On</b>.<br>";
}

// Disable register_globals to ensure security
ini_set('register_globals', '0');

// Begin LOADING INPUT VARS:
// used for all pages
	// name of current cp
	$cp = load_input_vars('cp');
	// page the user requested
	$url = load_input_vars('url');
	// user number (this is the user that is logged in's number/id)
	$number = load_input_vars('number');
	// web://cp user
	$user = load_input_vars('user');
	// bookmark
	$bookmark = load_input_vars('bookmark');
	//Confirmation of form submit
	$confirm = load_input_vars('confirm');
	// Form data
	$data = load_input_vars('data');
	// Action determines what code to execute after data is submitted (what action to take)
	$action = load_input_vars('action');
	// Domain, reseller and user ID variables
	$domid = load_input_vars('domid');
	$rid = load_input_vars('rid');
	$uid = load_input_vars('uid');

	$next = load_input_vars('next');
	$previous = load_input_vars('previous');
// End of LOADING INPUT VARS

// Set magic quotes runtime off (dont quote MySQL data)
set_magic_quotes_runtime(0);

// Ignore user abort, 60 seconds max allowed to a web interface script.
if ($cfg['httpd_mode'] != 'webcp') {
	ignore_user_abort();
}

//
// Setup Database Connection
@mysql_connect($cfg['dbhost'], $cfg['dbuser'], $cfg['dbpass'], true);
@mysql_select_db($cfg['dbname']);

// web-cp keeps track of users by setting a cookie
$webcp_tag = $_COOKIE['webcp_tag'];

// Detect the user's preferrences if set in a cookie
$skin_cookie = $_COOKIE['skin'];
$lang_cookie = $_COOKIE['lang'];

//
// Get currently used server name (name|ip) to generate cute(compatible) looking redirect header Location:
if ($cfg['ssl'])
	$web_name = "https://";
else
	$web_name = "http://";
//if ($_SERVER['HTTP_HOST'] AND !$cfg['cookiesec'])
	$web_name .= $_SERVER['HTTP_HOST'];
//else
//	$web_name .= $cfg['sysname'];
/*if ($_SERVER['HTTP_HOST'] AND !$cfg['cookiesec']) {
	$tmp = parse_url($web_name.$_SERVER['HTTP_HOST']);
	$web_name .= $tmp['host'];
}
else
	$web_name .= $cfg['sysname'];*/
if (!isset($cfg['supress_port'])) $cfg['supress_port']=false;
if ($cfg['port'] && !$cfg['supress_port'])
	$web_name .= ":".$cfg['port'];


//
// if web-cp cookie isn't set or it is a logout, stop on login screen
if ($webcp_tag && empty($data['failed'])) {

	// Check for the validity of the unique ID sent by cookie against the database
	unset($tmpdata);
	$dbp = mysql_query("SELECT timeout, type, remote_addr, suspend, ip_restrict, username, id FROM users WHERE webcp_tag='".$webcp_tag."'");
	$tmpdata = mysql_fetch_array($dbp);
	mysql_free_result($dbp);

	// fail if the tag is not recognized
	if (!$tmpdata) {
		$data['failed'] = "invalidtag";
	}
	// fail if the ID expired (Automated Unique ID timeout for security)
	if (time() > $tmpdata['timeout'] AND $tmpdata['type'] != "demo") {
		$data['failed'] = "timeout";
	}
	// fail if Remote user's IP is different than the IP recorded in DB (and not a demo user)
	if ($tmpdata['remote_addr'] != $_SERVER['REMOTE_ADDR'] AND $tmpdata['type'] != "demo") {
		$data['failed'] = "remote_addr";
	}

	// fail if user is suspended
	if ($tmpdata['suspend'] == "true") {
		$data['failed'] = "suspended";
	}

	// fail if Remote user's IP is different than ip restriction (if on)
	if ($tmpdata['ip_restrict'] AND !ereg("^".$tmpdata['ip_restrict'],$_SERVER['REMOTE_ADDR'])) {
		$data['failed'] = "ip_restrict";
	}
}
// Set Environment var: $userdata (contains info about the current user)
$userdata = fetchdata("*","user", array($tmpdata['username'], $tmpdata['id']));
unset($tmpdata);
if (!is_array($userdata)) return('init.inc.phps :: ERROR! no $userdata');
// if backend is down, follow instructions
if ((!(is_readable($cfg['basedir'].$cfg['statustag'])) || ((is_readable($cfg['basedir'].$cfg['statustag'])) && (fileatime($cfg['basedir'].$cfg['statustag']) < (time() - 90)))) && ($cfg['preventoutagelogins']) && ($userdata['level'] > 1)) {
	$data['failed'] = "backend";
	$message = "A user attempted to login to web-cp at $web_name and the backend was reported as down.";
	$subject = "web-cp backend down : $web_name";
	mail($cfg['adminmail'],$subject,$message, "X-Priority: 1\nImportance: High\nFrom: <".$cfg['adminmail'].">\n");
}

// if no $skin (layout), set user's preference:
$skin = str_replace("/","",load_input_vars('skin'));
if ($skin == '' || !file_exists("skin/".$skin)) {
	if (file_exists("skin/".$userdata['skin']) && $userdata['skin'] != '') {
		$skin = $userdata['skin'];
	} elseif (file_exists("skin/".$skin_cookie) && $skin_cookie != '') {
		$skin = $skin_cookie;
	} else {
		$skin = $cfg['defaultskin'];
	}
}

// Set up $framed and $framename so frames work in skins
$framed = str_replace('/', '', load_input_vars('framed'));
$framename = load_input_vars('framename');

// if no $lang (language), set user's preference:
if(isset($lang)) $lang = str_replace("/","",$lang);
if (!isset($lang) OR $lang == '' OR !file_exists("lang/".$lang.".phps")) {
	if (file_exists("lang/".$userdata['lang'].".phps") && $userdata['lang'] != '') {
		$lang = $userdata['lang'];
	} elseif (file_exists("lang/".$lang_cookie.".phps") && $lang_cookie != '') {
		$lang = $lang_cookie;
	} else {
		$lang = detect_user_language();
		if (!$lang) {
			$lang = $cfg['defaultlang'];
		}
	}
}

// Get favorite panel page and go there if needed.
$tmp = explode(":",$userdata['favorites']);
if (!trim($cp) AND trim($userdata['favorites'])) {
	$cp = $tmp[0];
	$url = $tmp[1];
	$number = $tmp[2];
	$user =  $tmp[3];
}

// Ensure we are logged in
if ($webcp_tag && empty($data['failed'])) {
// Set default cp if it is not set already
$cp = str_replace("/","",$cp);
if (!@is_dir($cp)) {
	$cp = "personal";
}
// if no $url (current page), set default:
$url = str_replace("/","",$url);
if (!trim($url)) {
	if ($cp == "personal")
		$url = "userinfo";
	elseif ($cp == "domain")
		$url = "domaininfo";
	elseif ($cp == "reseller")
		$url = "resellerinfo";
	elseif ($cp == "server")
		$url = "serverinfo";
	else
		$url = "index";
}
}

// Check $number validity and reset it if it's not okay.
if (!ereg($rx['num'],$number) OR ($number < 1000000000 AND $cp == 'domain'))
	$number = $userdata['id'];
if ($number AND $cp == 'domain') {
	$tmp = fetchdata("id","domain",$number);
	if (!$tmp)
		$number = $userdata['id'];
}
// Check $user validity and reset it if it's not ok.
if (!ereg($rx['user'],$user))
	$user = $userdata['username'];

global $resellerdata, $domaindata, $userdata, $personaldata;

// Load modules and call some hooks
load_modules();

$newcfg = array();
call_hook('web:cfg:default', $newcfg);
//$cfg += $newcfg;
array_concat($cfg, $newcfg, false);
call_hook('web:cfg:set', $cfg);

// Verify user access level and Set $cp Environment var: $personaldata, $domaindata, $resellerdata
// (contains info about the current panel viewed)
switch($cp) {
	case "tools":
		break;

	case "server":
		if ($userdata['level'] < 2) {
			break;
		}
		else
			$data['failed'] = "access";

	case "reseller":
		if ($userdata['level'] < 3) {
			$resellerdata = fetchdata("*","reseller",$number);
			if (substr($userdata['id'], 0, 5) != $resellerdata['id'] AND $userdata['level'] == '2') {
				$data['failed'] = "access";
				break;
			}
			if (!trim($userdata))
				return 'init.inc.phps :: ERROR! no $userdata';
			break;
		}
		else
			$data['failed'] = "access";

	case "domain":
		if ($userdata['level'] < 4) {
			// fetch domain data and reseller name
			$domaindata = fetchdata("*","domain",$number);
			if ($domaindata['type'] != 'domain') {
				// redirect to sub/pointer management page
				$domid = $number;
				$url = 'subpointer';
				$number = $domaindata['owner'];

				// reload parent domain's data
				$domaindata = fetchdata("*","domain",$domaindata['owner']);
			}

			$resellerdata = fetchdata("name","reseller",$domaindata['id']);

			if (!is_array($domaindata))
				return 'init.inc.phps :: ERROR! no $domaindata';
			if (!is_array($resellerdata))
				return 'init.inc.phps :: ERROR! no $resellerdata';
			if ($domaindata['type'] != 'domain')
				return'init.inc.phps :: ERROR! type "domain" only';

			// Verify user access validity.
			if ($userdata['level'] == 3) {
				if ($userdata['id'] != $domaindata['id'])
					$data['failed'] = "access";
			}
			elseif ($userdata['level'] == 2) {
				if (substr($userdata['id'], 0, 5) != $domaindata['owner'])
					$data['failed'] = "access";
			}
			elseif ($userdata['level'] > 2) {
				if ($domaindata['ip_restrict'] AND !ereg("^".$domaindata['ip_restrict'],$_SERVER['REMOTE_ADDR']))
					$data['failed'] = "ip_restrict";
			}
			break;
		}
		else
			$data['failed'] = "access";

	case "personal":
		if ($userdata['level'] < 5) {

			// fetch user data and reseller name
			$personaldata = fetchdata("*","user",array($user, $number));
			$domaindata = fetchdata("host,domain","domain",$personaldata['id']);
			$resellerdata = fetchdata("name","reseller",$personaldata['id']);
			if (!is_array($personaldata))
				return 'init.inc.phps :: ERROR! no $personaldata';
			if (!is_array($resellerdata))
				return 'init.inc.phps :: ERROR! no $resellerdata';

			// Verify user access validity in cases of domain and reseller administrators.
			if ($userdata['level'] > $personaldata['level']) {
				$data['failed'] = "access";
			}
			elseif ($userdata['level'] == 4) {
				if($user != $userdata['username'])
					$data['failed'] = "access";
			}
			elseif ($userdata['level'] == 3) {
				if ($userdata['id'] != $personaldata['id'])
					$data['failed'] = "access";
			}
			elseif ($userdata['level'] == 2) {
				if (substr($userdata['id'], 0, 5) != substr($personaldata['id'], 0, 5))
					$data['failed'] = "access";
			}
			$number = $personaldata['id'];
			break;
		}
		else
			$data['failed'] = "access";
}

$langpass = Array('userdata' => $userdata, 'personaldata' => $personaldata, 'domaindata' => $domaindata, 'resellerdata' => $resellerdata, 'lang' => $lang);
// Call language hook
call_hook('web:lang', $langpass);

// Construct valid url for self contained FORMS
global $current_url;
$current_url = "./?cp=$cp&url=$url&number=$number";
if ($user) $current_url .= "&user=$user";
if ($framed) $current_url .= "&framed=$framed&framename=$framename";
?>
